#include "ros.h"

Ros::Ros()
{
//    //init
//    system("sh /root/init.sh");
//    system("rm /root/init.sh");
//    //unzip
//    system("unzip /root/hmiPackage.zip -d /");
//    system("rm /root/hmiPackage.zip");

//    //
//    system("chmod 777 /etc/init.d/rsC");
//    system("chmod 777 /tcrwork");
//    system("chmod 777 /tcrwork/linuxControllerHmi/trunk/hmiController/bin/*");
//    system("chmod 777 /tcrwork/linuxControllerHmi/trunk/hmiController/lib/*");
//    system("chmod 777 /tcrwork/linuxControllerHmi/trunk/hmiController/data/*");

    //标志位
    dat.forkFlag = 0;//初始化

    //QTimer
    rosTimer = new QTimer;
    connect(rosTimer,SIGNAL(timeout()),this, SLOT(rosTimeWork()));
    rosTimer->start(1000);

    qDebug() << "---init ros---";
}

void Ros::rosTimeWork()
{
    if(0 == dat.forkFlag)
    {
        //初次启动

        system("for var in /tcrwork/linuxControllerHmi/trunk/hmiController/lib/*so.1.0.0;do mv $var ${var%so.1.0.0}so.1;done");

        //system("mv /tcrwork/hmiMain/hmiMain /tcrwork/hmiMain/hmi");
        system("chmod 777 /tcrwork/linuxControllerHmi/trunk/hmiController/bin/hmi.sh");
        system("sh /tcrwork/linuxControllerHmi/trunk/hmiController/bin/hmi.sh");

        dat.forkFlag = 1;
    }
    else if(1 == dat.forkFlag)
    {
        //正常工作
        if(dat.heartStatus)
        {
            dat.heartCount = 0;
            dat.heartStatus = false;//dog
        }
        else
        {
            dat.heartCount++;
        }
        //qDebug()<<"heartCount:"<<dat.heartCount;

        if(dat.heartCount > 15)
        {
            dat.forkFlag = -1;
        }
    }
    else if(2  == dat.forkFlag)//调用校准
    {
        system("killall hmiMain");
        system("echo killall hmiMain $?");

        system("killall /tcrwork/linuxControllerHmi/trunk/hmiController/bin/hmiMain");
        system("echo killall /tcrwork/linuxControllerHmi/trunk/hmiController/bin/hmiMain $?");

        system("rm /etc/pointercal");
        system("echo rm /etc/pointercal $?");

        system("sleep 0.1");
        system("echo sleep 0.1 $?");

        system("/opt/tslib/bin/ts_calibrate");
        system("echo /opt/tslib/bin/ts_calibrate $?");

        system("killall ts_calibrate");
        system("echo killall ts_calibrate $?");

        dat.forkFlag = 0;//重启
    }
    else if(3  == dat.forkFlag)//重启系统
    {
        system("killall  hmi");

        system("sleep 1");
        system("echo sleep 1 $?");

        system("echo '0'>/tcrwork/forkflag.data");//重启

        system("reboot");
    }
    else
    {
        qDebug()<<"bug error!";
        //崩溃状况或者意外退出
        //记录日志
        //重启程序
        dat.forkFlag = 0;

        dat.heartStatus = true;
        dat.heartCount = 0;
    }
}
